package com.wanhe.base.util;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.wanhe.base.R;

import java.util.Timer;
import java.util.TimerTask;


public class ViewUtil {

	public static final String COLOR_CHAT_NAME = "#8162b0";
	public static final String COLOR_CHAT_CONTENT = "#ebe8fa";

	public static int getScreenWidth(Activity act) {
		DisplayMetrics metrics = new DisplayMetrics();
		act.getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return metrics.widthPixels;
	};

	public static int getScreenHeight(Activity act) {
		DisplayMetrics metrics = new DisplayMetrics();
		act.getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return metrics.heightPixels;
	};

	public static Point getScreenPoint(Activity act) {
		DisplayMetrics metrics = new DisplayMetrics();
		act.getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return new Point(metrics.widthPixels, metrics.heightPixels);
	};
	
	public static void ShortToast(Activity context, final String str) {
		if(!context.isFinishing()){
		if(str != null){
			Toast toast = Toast.makeText(context, str,
					Toast.LENGTH_SHORT);
			toast.show();
		}
	}
	}

	public static void ShortToast(Context mContext,final String str) {
		if(str != null){
			Toast toast = Toast.makeText(mContext, str,
					Toast.LENGTH_SHORT);
			toast.show();
		}

	}

	public static void LongToast(Context mContext,String str) {
		if(str != null){
		Toast toast = Toast.makeText(mContext, str,
				Toast.LENGTH_LONG);
		toast.show();
		}
	}

	public static void ShortToast(Context mContext,final int res) {
		Toast toast = Toast.makeText(mContext, res,
				Toast.LENGTH_SHORT);
		toast.show();
	}

	public static void LongToast(Context mContext,int res) {
		Toast toast = Toast.makeText(mContext, res,
				Toast.LENGTH_LONG);
		toast.show();
	}

	public static int getXmlIntValue(Context context, int id) {
		TypedValue typedValue = new TypedValue();
		context.getResources().getValue(id, typedValue, true);
		return (int) TypedValue.complexToFloat(typedValue.data);
	}

	public static float getXmlFloatValue(Context context, int id) {
		TypedValue typedValue = new TypedValue();
		context.getResources().getValue(id, typedValue, true);
		return TypedValue.complexToFloat(typedValue.data);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip( Context mContext,float pxValue) {
		final float scale = mContext.getResources().getDisplayMetrics().density;
		Log.i("ViewUtils", "Scale" + scale);
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context mContext, float dpValue) {
		final float scale = mContext.getResources().getDisplayMetrics().density;
		Log.i("ViewUtils", "Scale" + scale);
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 sp 的单位 转成为 px(像素)
	 */
	public static int sp2px(Context mContext,float spValue) {
		float fontScale = mContext.getResources().getDisplayMetrics().scaledDensity;
		Log.i("ViewUtils", "fontScale" + fontScale);
		return (int) (spValue * fontScale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 sp
	 */
	public static int px2sp( Context mContext,float pxValue) {
		float fontScale = mContext.getResources().getDisplayMetrics().scaledDensity;
		Log.i("ViewUtils", "fontScale" + fontScale);
		return (int) (pxValue / fontScale + 0.5f);
	}

	/**
	 * change dip value to pixel value for certain screen size
	 * 
	 * @param dipValue
	 * @param context
	 * @return
	 */
	public static int getPixels(int dipValue, Context context) {
		int result = 0;
		Resources res = context.getResources();
		result = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				dipValue, res.getDisplayMetrics());
		return result;
	}

	/**
	 * 创建PopupWindow
	 * 
	 * @param context
	 * @param width
	 * @param height
	 * @param view
	 * @param isOutsideTouchable
	 * @param isFocusable
	 * @param background
	 * @return
	 */
	public static PopupWindow createPopupWindow(Context context, int width,
                                                int height, View view, boolean isOutsideTouchable,
                                                boolean isFocusable, Drawable background) {
		PopupWindow ppw = new PopupWindow(context);
		ppw.setWidth(width);
		ppw.setHeight(height);
		ppw.setFocusable(isFocusable);
		ppw.setOutsideTouchable(isOutsideTouchable);
		ppw.setBackgroundDrawable(background);
		ppw.setContentView(view);
		return ppw;
	}

	/**
	 * 创建PopupWindow
	 *
	 * @param context
	 * @param view
	 * @return
	 */
	public static PopupWindow createPopupWindow(Context context, View view){
		PopupWindow ppw = new PopupWindow(context);
		ppw.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
		ppw.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
		ppw.setFocusable(true);
		ppw.setOutsideTouchable(true);
		ppw.setBackgroundDrawable(new BitmapDrawable());
		ppw.setContentView(view);
		return ppw;
	}


	/**
	 * Text to SpannableString
	 * 
	 * @return
	 */
	public static SpannableString getContenToSpannable(String content, String parseColor) {
		if (TextUtils.isEmpty(content)) {
			return null;
		}
		SpannableString sb = new SpannableString(content);
		sb.setSpan(new ForegroundColorSpan(Color.parseColor(parseColor)), 0, content.length(),
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		return sb;
	}
	
	public static SpannableString getChatNameBySpann(String name){
		return getContenToSpannable(name, COLOR_CHAT_NAME);
	}
	
	public static SpannableString getChatContentBySpann(String name){
		return getContenToSpannable(name, COLOR_CHAT_CONTENT);
	}


	static int mProgress = 0;
	static Dialog dialog;
	static Timer timer;

	public static Dialog loadingDialog(final Activity context) {
		if(dialog!=null&&dialog.isShowing()){
			dialog.dismiss();
		}
		View view = LayoutInflater.from(context).inflate(R.layout.custom_loading, null);
		ImageView imageView = (ImageView) view.findViewById(R.id.iv_progress);
		final Drawable mClipDrawable = imageView.getDrawable();
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				context.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if (mProgress > 10000) {
							mProgress = 0;
						}
						mClipDrawable.setLevel(mProgress);
						mProgress += 100;
					}
				});
			}
		}, 0, 20);
		dialog = getCustomDialog(context, view);
		dialog.show();
		return dialog;
	}

	public static void dismissLoadingDialog() {
		if (dialog != null) {
			if (timer != null) {
				timer.cancel();
				timer = null;
			}
			mProgress = 0;
			dialog.dismiss();
			dialog = null;
		}
	}
//	/**
//	 * create custom dialog,it will show when we call the display method
//	 *
//	 * @param context
//	 * @param message
//	 *            content message
//	 * @param title
//	 *            dialog title message
//	 * @param positiveButtonText
//	 *            positive button text
//	 * @param negativeButtonText
//	 *            negative button text
//	 * @param posListener
//	 *            positive button click listener
//	 * @param negListener
//	 *            negative button click listener
//	 * @return CustonDialog object
//	 */
//	public static Dialog getAlertDialog(Context context, String message,
//                                        String title, String positiveButtonText, String negativeButtonText,
//                                        DialogInterface.OnClickListener posListener,
//                                        DialogInterface.OnClickListener negListener) {
//
//		AlertDialog.Builder buidler = new AlertDialog.Builder(context);
//		buidler.setMessage(message);
//		buidler.setTitle(title);
//		buidler.setPositiveButton(positiveButtonText, posListener);
//		buidler.setNegativeButton(negativeButtonText, negListener);
//
//		return buidler.create();
//	}
//	public static Dialog getAlertDialog(Context context, String message,
//                                        String title) {
//
//		AlertDialog.Builder buidler = new AlertDialog.Builder(context);
//		buidler.setMessage(message);
//		buidler.setTitle(title);
//		buidler.setPositiveButton( context.getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				if(dialog!=null){
//					dialog.dismiss();
//				}
//			}
//		});
//
//		return buidler.create();
//	}
//
//	public static Dialog getAlertDialog(Context context, String message,
//                                        String title, String positiveButtonText,
//                                        DialogInterface.OnClickListener posListener
//										) {
//
//		AlertDialog.Builder buidler = new AlertDialog.Builder(context);
//		buidler.setMessage(message);
//		buidler.setTitle(title);
//		buidler.setPositiveButton(positiveButtonText, posListener);
//		buidler.setNegativeButton(context.getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				if(dialog!=null){
//					dialog.dismiss();
//				}
//			}
//		});
//
//		return buidler.create();
//	}
//
//	public static Dialog getCustomDialog(Activity context, int layoutId){
//		Dialog dialog = new Dialog(context, R.style.dialogTheme);
//		dialog.setContentView(layoutId);
////		dialog.setTitle("Custom Dialog");
//        /*
//         * 获取圣诞框的窗口对象及参数对象以修改对话框的布局设置,
//         * 可以直接调用getWindow(),表示获得这个Activity的Window
//         * 对象,这样这可以以同样的方式改变这个Activity的属性.
//         */
//		Window dialogWindow = dialog.getWindow();
//		dialogWindow.setGravity(Gravity.CENTER);
//        /*
//         * 将对话框的大小按屏幕大小的百分比设置
//         */
//        WindowManager m = context.getWindowManager();
//        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
//        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
//        p.height =  WindowManager.LayoutParams.WRAP_CONTENT;
//        p.width = (int) (d.getWidth() * 0.8); // 宽度设置为屏幕的0.65
//        dialogWindow.setAttributes(p);
//		dialog.show();
//
//        /*
//         * lp.x与lp.y表示相对于原始位置的偏移.
//         * 当参数值包含Gravity.CENTER_HORIZONTAL时
//         * ,对话框水平居中,所以lp.x就表示在水平居中的位置移动lp.x像素,正值向右移动,负值向左移动.
//         * 当参数值包含Gravity.CENTER_VERTICAL时
//         * ,对话框垂直居中,所以lp.y就表示在垂直居中的位置移动lp.y像素,正值向右移动,负值向左移动.
//         * gravity的默认值为Gravity.CENTER,即Gravity.CENTER_HORIZONTAL |
//         * Gravity.CENTER_VERTICAL.
//
//         */
////		lp.x = 100; // 新位置X坐标
////		lp.y = 100; // 新位置Y坐标
////		lp.width = 300; // 宽度
////		lp.height = 300; // 高度
////		lp.alpha = 0.7f; // 透明度
//
//		// 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
//		// dialog.onWindowAttributesChanged(lp);
////		dialogWindow.setAttributes(lp);
//     return dialog;
//	}
//	public static Dialog getCustomDialog(Activity context, View view){
//		Dialog dialog = new Dialog(context,R.style.dialogTheme);
//		dialog.setContentView(view);
//        /*
//         * 获取圣诞框的窗口对象及参数对象以修改对话框的布局设置,
//         * 可以直接调用getWindow(),表示获得这个Activity的Window
//         * 对象,这样这可以以同样的方式改变这个Activity的属性.
//         */
//		Window dialogWindow = dialog.getWindow();
//		dialogWindow.setGravity(Gravity.CENTER);
//        /*
//         * 将对话框的大小按屏幕大小的百分比设置
//         */
//		WindowManager m = context.getWindowManager();
//		Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
//		WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
//		p.height =  WindowManager.LayoutParams.WRAP_CONTENT;
//		p.width = (int) (d.getWidth() * 0.9); // 宽度设置为屏幕的0.9
//		dialogWindow.setAttributes(p);
////		dialog.show();
//		return dialog;
//	}
public static Dialog getCustomDialog(Activity context, View view){
	Dialog dialog = new Dialog(context,R.style.dialogTheme);
	dialog.setContentView(view);
        /*
         * 获取圣诞框的窗口对象及参数对象以修改对话框的布局设置,
         * 可以直接调用getWindow(),表示获得这个Activity的Window
         * 对象,这样这可以以同样的方式改变这个Activity的属性.
         */
	Window dialogWindow = dialog.getWindow();
	dialogWindow.setGravity(Gravity.CENTER);
	dialog.setCancelable(false);
        /*
         * 将对话框的大小按屏幕大小的百分比设置
         */
	WindowManager m = context.getWindowManager();
	Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
	WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
	p.height =  WindowManager.LayoutParams.WRAP_CONTENT;
	p.width = WindowManager.LayoutParams.WRAP_CONTENT; // 宽度设置为屏幕的0.9
	dialogWindow.setAttributes(p);
//		dialog.show();
	return dialog;
}

	public static Dialog getCustomDialog(Activity context, int view, int style){
		Dialog dialog = new Dialog(context,style);
		dialog.setContentView(view);
        /*
         * 获取圣诞框的窗口对象及参数对象以修改对话框的布局设置,
         * 可以直接调用getWindow(),表示获得这个Activity的Window
         * 对象,这样这可以以同样的方式改变这个Activity的属性.
         */
		Window dialogWindow = dialog.getWindow();
		dialogWindow.setGravity(Gravity.CENTER);
        /*
         * 将对话框的大小按屏幕大小的百分比设置
         */
		WindowManager m = context.getWindowManager();
		Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
		WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
		p.height =  WindowManager.LayoutParams.WRAP_CONTENT;
		p.width = (int) (d.getWidth() * 0.9); // 宽度设置为屏幕的0.9
		dialogWindow.setAttributes(p);
//		dialog.show();
		return dialog;
	}
//	 public static CustomAlertDialog.Builder createProgressDialog(Context
//	 context,String prompt){
//	 CustomAlertDialog.Builder dialog = new
//	 CustomAlertDialog.Builder(context);
//	 final View view =
//	 LayoutInflater.from(context).inflate(R.layout.layout_progress_loading,
//	 null);
//	 if(!TextUtils.isEmpty(prompt)){
//	 ((TextView)view.findViewById(R.id.progress_text)).setText(prompt);
//	 }
//	 dialog.setView(view);
//	 return dialog;
//	 }
	@SuppressLint("NewApi")
//	public static void setStatusBarColor(Context activity, Window window,
//			int colorResID) {
//		if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
//			setTranslucentStatus(window, true);
//		}
//
//		SystemBarTintManager tintManager = new SystemBarTintManager(activity,
//				window);
//		tintManager.setStatusBarTintEnabled(true);
//
//		if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT
//				&& tintManager != null) {
//			tintManager.setStatusBarTintResource(colorResID);
//		} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//			window.setStatusBarColor(activity.getResources().getColor(
//					colorResID));
//		}

//	}

	@TargetApi(19)
	private static void setTranslucentStatus(Window win, boolean on) {
		if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
			WindowManager.LayoutParams winParams = win.getAttributes();
			final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
			if (on) {
				winParams.flags |= bits;
			} else {
				winParams.flags &= ~bits;
			}
			win.setAttributes(winParams);
		}
	}

}
